import React from 'react';
import { Select,Upload, Radio,DatePicker ,message, Checkbox, Button, InputNumber,Input, Form, Icon,Cascader } from 'antd';
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const FormItem = Form.Item;
import { createPatient,fetchPatients,fetchPatient,updatePatient,changePage,_validate,formItemLayout,fetchArgs,FetchURL,fetchData } from '../store/actions';

class FormEditPatient extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            patient:null,
            patientFetch: true,
            isModal:this.props.isModal,
            regionDefaultValue:[],//省市区默认值
            regionValue: ''//省市区选中值
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.resetFields = this.resetFields.bind(this);
        this.fetchRegion=this.fetchRegion.bind(this);
        this.onRegionChange = this.onRegionChange.bind(this);
    }
    fetchRegion(){
        const _this = this;
        let _args = Object.assign({},fetchArgs);
        _args.URL = FetchURL.REGION;
        _args.IsAuth = true;
        _args.Succ = function (res) {
            let _data = [];
            res.content.map(_=>{
                let entry = _;//JSON.parse(_);
                let province = { value:entry.id, label: entry.name };
                province.children = [];
                for(let i = 0; i < entry.cities.length; i++ ){
                    let city = { value:entry.cities[i].id, label: entry.cities[i].name};
                    city.children = [];
                    for(let j = 0; j < entry.cities[i].areas.length; j++ ){
                        let area = { value:entry.cities[i].areas[j].id, label: entry.cities[i].areas[j].name};
                        city.children.push(area);
                    }
                    province.children.push(city);
                }
                _data.push(province);
            });
            _this.setState({
                data:_data,
            });
        };
        _this.props.dispatch(fetchData(_args));
    };
    resetFields(){
        this.props.form.resetFields()
    }
    static contextTypes = {
        router:React.PropTypes.object
    };
    handleSubmit(e) {
        e.preventDefault();
        const _this = this,
            uid = _this.props.user.user.user_id,
            pid = _this.props._id,
            status = 1,
            opts = {
                userid: uid,
                status: status
            };
        _validate(e,_this,function(v){
            const _v = Object.assign({},v,{birthday:v.birthday});
            if(_v.birthday) {
                let type = typeof _v.birthday;
                let t = type === 'object' ? _v.birthday : new Date(_v.birthday);
                _v.birthday = `${t.getFullYear()}-${(t.getMonth() + 1)}-${t.getDate()} ${t.getHours()}:${t.getMinutes()}:${t.getSeconds()}`;
            }
            let _region = _this.state.regionValue;
            if(!_v.address)
                _v.address = '';
            if(_region && _region.length > 0){
                _region = _region + _v.address;
            }else {
                _region = '$' + '$' + _v.address;
            }
            _v.address = _region;
            if(pid){
                _this.props.dispatch(updatePatient(pid,_v,function(res){
                    message.success('修改亲友成功',1,function(){
                        _this.resetFields();
                        if(_this.state.isModal){
                            _this.props.onSub(res.content);
                        }
                        _this.props.dispatch(fetchPatient(pid,function(res){
                            _this.setState({
                                patient:res.content
                            },function(){
                                _this.context.router.push('/patients')
                            })
                        }));
                    });
                },function(res){
                    message.error(`出错了！！${res.head.msg}`,1)
                }))
            }else{
                _this.props.dispatch(createPatient(uid,_v,function(res){
                    message.success('创建亲友成功',1,function(){
                        _this.resetFields();
                        if(_this.state.isModal){
                            _this.props.onSub(res.content)
                        }else{
                            _this.props.dispatch(fetchPatients(opts));
                            _this.context.router.push('/patients')
                        }
                    });
                },function(res){
                    message.error(`出错了！！${res.head.msg}`,1)
                }))
            }
        })
    }
    componentWillMount(){
        this.fetchRegion();
        const _this = this,
            pid = this.props._id;
        const {setFieldsValue} = this.props.form;

        if (pid) {
            _this.props.dispatch(fetchPatient(pid,function(res){
                const patient = res.content;
                if(patient.birthday) {
                    let type = typeof patient.birthday;
                    let t = type === 'object' ? patient.birthday : new Date(patient.birthday);
                    patient.birthday = t;
                }
                //处理地址
                let _regionDefaultValue = [];
                let _address = patient.address;//详细地址
                let _regionValue = '' //地区级联值
                let _regionLabel = '' //地区级联值
                if(_address == {} || !_address)
                    _address = '';
                if(_address.split('$').length >= 3){
                    _regionValue = _address.split('$')[0];
                    _regionLabel = _address.split('$')[1];
                    if(_regionValue.split(',').length > 0){
                        _regionDefaultValue = _address.split('$')[0].split(',');
                        if(_regionDefaultValue.length > 0 && _regionDefaultValue[0] != '')
                            _regionDefaultValue[0] = parseInt(_regionDefaultValue[0]);//省份必须要转为int才能查找到
                    }
                    _address = _address.split('$')[2];
                }else {
                    _address = _address;
                }
                patient.address = _address;
                _this.setState({
                    patient:patient,
                    patientFetch: false,
                    regionDefaultValue: _regionDefaultValue,
                    regionValue: _regionValue + '$' + _regionLabel + '$',
                    pRelationship:patient.relationship == '本人'?1:0
                },function(){
                    setFieldsValue(patient)
                    console.log('关系',_this.state.pRelationship)
                })
            }))
        }else{
            _this.setState({
                patient:null,
                patientFetch: false
            },function(){
                setFieldsValue()
            })
        }
    }
    onRegionChange(value, selectedOptions){
        let _regionValue = value.join(',');
        let _regionLabel = selectedOptions.map((item, i) => {
            const option = selectedOptions[i];
            return option.label;
        }).join('/');
        console.log('_regionValue',_regionValue);
        console.log('_regionLabel',_regionLabel);
        this.setState({
            regionValue: _regionValue + '$' + _regionLabel + '$'
        });
    }
    onCancel(){
        if(this.state.isModal){
            this.props.onCancel()
        }else{
            this.context.router.goBack(-1)
        }
    }
    render() {
        const { getFieldProps } = this.props.form;
        const disabledDate = function (current) {
            return current && current.getTime() > Date.now();
        };
        const newPatientName = getFieldProps('name', {
            rules: [
                { required: true, message: '请输入亲友的姓名'}
            ]
        });
        const newPatientSex = getFieldProps('gender', {
            rules: [
                { required: true, message: '请选择亲友的性别' }
            ]
        });
        const newPatientBirthday = getFieldProps('birthday', {
            rules: [
                { required: true,
                    type: 'date', message: '请设置亲友的生日' }
            ]
        });
        const newPatientRelation = getFieldProps('relationship', {
            rules: [
                { required: true,message: '请设置亲友与您的关系' }
            ]
        });
        const newPatientMobile = getFieldProps('mobile', {
            rules: [
                { required: false,message: '请输入亲友手机号' }
            ]
        });
        const newPatientIDCard = getFieldProps('idcard', {
            rules: [
                { required: false,min:18,max:18,message: '身份证号是18位' }
            ],
            validateTrigger:'onBlur'
        });
        const newSocial_Insurance = getFieldProps('social_insurance', {
            rules: [
                { required: false,message: '社保卡号' }
            ]
        });
        const newPatientAddress = getFieldProps('address', {
            rules: [
                { required: false,message: '请输入亲友地址' }
            ]
        });
        const medical_history = getFieldProps('medical_history', {
            rules: [
                { required: false,message: '请输入过往病史' }
            ]
        });
        const relationshipList = (function(t){
            const _pr = t.state.pRelationship;
            if(_pr == 1){
                return (
                  <RadioGroup {...newPatientRelation}>
                      <RadioButton value="本人">本人</RadioButton>
                  </RadioGroup>
                )
            }else{
                return (
                  <RadioGroup {...newPatientRelation}>
                      <RadioButton value="父母">父母</RadioButton>
                      <RadioButton value="子女">子女</RadioButton>
                      <RadioButton value="朋友">朋友</RadioButton>
                      <RadioButton value="其他">其他</RadioButton>
                  </RadioGroup>
                )
            }
        })(this);
        if(this.state.patientFetch){
            return (<div>loading...</div>)
        }else{
            const _formItemLayout = this.state.isModal ? (formItemLayout.ignore) : formItemLayout;
            return (
              <Form horizontal form={this.props.form}>
                  <div>
                      <FormItem
                        {..._formItemLayout}
                        label="关系"
                      >
                          {relationshipList}
                      </FormItem>
                      <FormItem
                        {..._formItemLayout}
                        label="姓名"
                      >
                          <Input {...newPatientName} />

                      </FormItem>
                      <FormItem
                        {..._formItemLayout}
                        label="性别"
                      >
                          <RadioGroup {...newPatientSex}>
                              <RadioButton value="M">男</RadioButton>
                              <RadioButton value="F">女</RadioButton>
                          </RadioGroup>
                      </FormItem>
                      <FormItem
                        {..._formItemLayout}
                        label="出生日期"
                      >
                          <DatePicker {...newPatientBirthday} disabledDate={disabledDate} format="yyyy-MM-dd" />
                      </FormItem>
                      <FormItem
                        {..._formItemLayout}
                        label="身份证号"
                      >
                          <Input {...newPatientIDCard} />
                      </FormItem>
                      <FormItem {..._formItemLayout} label="社保卡号">
                          <Input {...newSocial_Insurance} />
                      </FormItem>
                      <FormItem
                        {..._formItemLayout}
                        label="手机号"
                      >
                          <Input {...newPatientMobile} />
                      </FormItem>
                      <FormItem {..._formItemLayout} label="所在地区：">
                          <Cascader changeOnSelect={true} options={this.state.data && this.state.data} defaultValue={this.state.regionDefaultValue && this.state.regionDefaultValue} onChange={this.onRegionChange} placeholder="请选择所在地区" />
                      </FormItem>
                      <FormItem {..._formItemLayout} label="详细地址：">
                          <Input {...newPatientAddress} placeholder="请输入详细地址"  />
                      </FormItem>
                      <FormItem {..._formItemLayout} label="过往病史" help="">
                          <Input type="textarea" {...medical_history} placeholder="请输入过往病史" autosize={{ minRows:8, maxRows: 12 }}/>
                      </FormItem>
                      <FormItem wrapperCol={_formItemLayout.noLabel}>
                          <Button type="primary" onClick={this.handleSubmit}>保存</Button>
                          &nbsp;&nbsp;&nbsp;&nbsp;
                          <Button
                            type="light"
                            onClick={this.onCancel.bind(this)}
                          >
                              取消
                          </Button>
                      </FormItem>
                  </div>
              </Form>
            )
        }
    }

}

export default FormEditPatient = Form.create()(FormEditPatient);